import { Injectable,NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Prisma, course_type } from '@prisma/client';
@Injectable()
export class CourseContentService {
    constructor(private readonly prisma: PrismaService) {}
   async getContent(chapterId:string,type:string){
    const data     =  await  this.prisma.course_chapter.findFirst({
            where:{
                id:chapterId
            },
            include:{
                course:true,
                content:{
                    orderBy:{
                        order:'asc'
                    }
                },
            },
        })
    if(!data){
        throw new NotFoundException('课程不存在');
    }
    if(!data.content){
        throw new NotFoundException('课程不存在');
    }
    if(type !=='choice'){
        return data;
    }
   const content = await Promise.all(data.content.map(async (item) => {
    let randomContents = await this.prisma.$queryRaw`
      SELECT * FROM "course_content" WHERE "isJz" = 0 ORDER BY RANDOM() LIMIT 3
    ` as Array<any>;
    if(!randomContents){
        throw new NotFoundException('课程内容不存在');
    }
    randomContents.push(item);
    randomContents.sort(() => Math.random() - 0.5);
    return {
      ...item,
      randomContents
    };
   }));
   return {
    ...data,
    content
   }
}
}
